package com.aaa.mbs.task;

import com.aaa.mbs.entity.LocalMessage;
import com.aaa.mbs.service.LocalMessageService;
import com.aaa.mbs.util.SenderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * fileName:CheckMQLocalMessage
 * description: 兜底方案，防止MQ中途出现故障，保证每个消息都可以发送到MQ，
 *              轮训本地消息表对没有发送消息重发,每隔30秒轮训一次
 * author: LJV
 * createTime:2021/1/22 15:34
 * version:1.0.0
 */

@Component
public class CheckMQLocalMessage {

    @Resource
    private SenderService senderService;

    @Autowired
    private LocalMessageService messageService;

    /**
     * 兜底方案:必须保证每个消息都发送到MQ消费端进行消费，保证数据最终一致
     *  每隔30秒检查本地消息表没有发送成功的消息，进行重试再次发送到MQ
     */
    @Scheduled(fixedDelay = 1000*30L)
    public void checkMQLocalMessage(){
        LocalMessage localMessage=new LocalMessage();
        localMessage.setState(LocalMessage.L_M_STATE_FAIL);
        List<LocalMessage> failStates =(List<LocalMessage>) messageService.queryAll(localMessage).getData();
        if(failStates!=null&&failStates.size()>0){
            failStates.stream().forEach(messageFailstate->{
                senderService.send(messageFailstate.getContent(), String.valueOf(messageFailstate.getId()));
            });
        }

    }
}
